<template>
    <div>
        <el-button type="success" @click="checkSuccess()">一键审核通过</el-button>
        <el-button type="primary" @click="isShowDialog('insert')">创建采购计划</el-button>
        <el-popover placement="bottom-start" width="1000" style="box-shadow: 0 0 8px rgba(0,0,0,.5);" trigger="click">
        <el-form :inline="true" :model="keywords">
                <el-form-item label="bom名称" >
                        <el-autocomplete  class="inputSuffix"  v-model="keywords.bom" :fetch-suggestions="searchAsyncBom" placeholder="请输入bom名称" @select="changeBom"></el-autocomplete>
                </el-form-item>
                <el-form-item label="供应商名称">
                    <el-autocomplete  class="inputSuffix"  v-model="keywords.supplier" :fetch-suggestions="searchAsyncSupplier" placeholder="请输入供应商名称" @select="changeSupplier"></el-autocomplete>
                </el-form-item>
                    <el-form-item label="令号">
                    <el-input v-model="keywords.makeNo"  ></el-input>
                </el-form-item>
                <el-button type="primary" @click="searchData" icon="el-icon-search">查询</el-button>
            </el-form>
        <el-button slot="reference" type="primary">查询</el-button>
    </el-popover>

        <!-- 表格 -->
        <el-table :data="tableData" :highlight-current-row="true" stripe border class="table-index"  style="width: 100%;" :height="tableHeight"
        :header-cell-style="getRowClass" v-loading="loading"   @selection-change="handleSelectionChange">
             <el-table-column type="selection" width="55" :selectable='selectable'></el-table-column>
            <el-table-column prop="supplierName" label="供应商名称"   min-width="140"></el-table-column>
            <el-table-column prop="makeNo" label="令号"  min-width="80"></el-table-column>
            <el-table-column prop="bomName" label="物料名称"   show-overflow-tooltip min-width="140"></el-table-column>
            <el-table-column prop="needNums" label="需求数量"   min-width="90"></el-table-column>
            <el-table-column prop="minPurchase" label="最小采购量"   min-width="90"></el-table-column>
            <el-table-column prop="actNums" label="实际采购量"   min-width="90"></el-table-column>
            <el-table-column prop="price" label="单价"   min-width="70"></el-table-column>
            <el-table-column prop="total" label="总价" min-width="70"></el-table-column>
            <el-table-column prop="planArriveDate" label="计划到货时间"   min-width="140" :formatter="timesFormatter"></el-table-column>
            <el-table-column prop="orderDate" label="计划下单日期"   min-width="120"  :formatter="timesFormatter"></el-table-column>
            <el-table-column prop="payDate" label="计划付款时间"   min-width="120"  :formatter="timesFormatter"></el-table-column>
            <el-table-column prop="state" label="订单状态" fixed="right"   min-width="90" align="center">
                <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.state==1">审核通过</el-tag>
                    <el-tag type="warning" v-else>审核中...</el-tag>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作"  align="center" width="140">
                <template slot-scope="scope">
                    <el-button @click="isShowDialog('update',scope.row)" type="text" size="mini">编辑</el-button>
                    <el-button @click="checkedPass(scope.row)" type="text" size="mini" v-if="scope.row.state===0">审核通过</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pagination.currentPage" :page-sizes="[5,10, 15,20, 25,30,50, 100]" :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"></el-pagination>
       <el-dialog :title="dialog.title" width="450px" center :visible.sync="dialog.isShow" :close-on-click-modal="false">
            <div :style="tableDialogHeightTabPane">
            <el-form class="demo-form-inline" v-model="dialogForm" label-position="right" label-width="120px">
                <el-form-item label="图纸类型">
                    <el-select v-model="dialogForm.type" placeholder="请选择图纸类型">
                        <el-option :label="item.name" :value="item.id" v-for="item in allMachineType" :key="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="数量">
                    <el-input-number v-model="dialogForm.num" controls-position="right" @change="handleChange" :min="1"></el-input-number>
                </el-form-item>
                <el-form-item label="令号"><el-input v-model="dialogForm.makeNo" ></el-input></el-form-item>
                <el-form-item label="需求日期"><el-date-picker v-model="dialogForm.needDate" type="date" placeholder="选择日期"> </el-date-picker></el-form-item>
            </el-form>
                </div>
            <div slot="footer" class="dialog-footer" style="text-align: center;">
                <el-button @click="createPlan" type="primary">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog :title="dialog1.title" width="800px" center :visible.sync="dialog1.isShow" :close-on-click-modal="false">
            <div :style="tableDialogHeightTabPane">
            <el-form class="demo-form-inline" v-model="dialogForm1" label-position="right" label-width="140px" :inline="true">
                <el-form-item label="供应商名称">
                    <el-autocomplete  class="autocomplete-row" v-model="dialogForm1.supplierName" :fetch-suggestions="querySearchAsync1" placeholder="请输入物料名称" @select="handleSelect1"></el-autocomplete>
                </el-form-item>
                <el-form-item label="物料名称"><el-input v-model="dialogForm1.bomName" disabled></el-input></el-form-item>
                <el-form-item label="令号"><el-input v-model="dialogForm1.makeNo" disabled></el-input></el-form-item>
                <el-form-item label="需求数量"><el-input v-model="dialogForm1.needNums" ></el-input></el-form-item>
                <!-- <el-form-item label="库存数量"><el-input v-model="dialogForm1.inventoryNums" ></el-input></el-form-item> -->
                <el-form-item label="单价"><el-input v-model="dialogForm1.price"></el-input></el-form-item>
                <el-form-item label="总价"><el-input v-model="dialogForm1.total" ></el-input></el-form-item>
                <el-form-item label="计划到货时间">
                      <el-date-picker  v-model="dialogForm1.planArriveDate" type="date" placeholder="选择日期"></el-date-picker>
                </el-form-item>
                <el-form-item label="计划下单日期">
                     <el-date-picker  v-model="dialogForm1.orderDate" type="date" placeholder="选择日期"></el-date-picker>
                </el-form-item>
                 <el-form-item label="计划付款时间">
                     <el-date-picker  v-model="dialogForm1.payDate" type="date" placeholder="选择日期"></el-date-picker>
                </el-form-item>
                 <!-- <el-form-item label="审核是否通过">
                    <el-select v-model="dialogForm1.status" placeholder="请选择">
                        <el-option :label="item.label" :value="item.value" v-for="item in isCheckedList" :key="item.label"></el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item label="创建人"><el-input v-model="dialogForm1.creatorName" disabled></el-input></el-form-item>
                  <el-form-item label="创建时间"><el-input v-model="dialogForm1.createTime" disabled></el-input></el-form-item>
            </el-form>
                </div>
            <div slot="footer" class="dialog-footer" style="text-align: center;">
                <el-button @click="submitClick" type="primary">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import cgbHttp from '@/axios/cgbHttp.js'
export default {
    data(){
        return {
            tableHeight: document.documentElement.clientHeight - 170,/**表格高度 */
            tableDialogHeightTabPane:{/**dialog style */
                height: (document.documentElement.clientHeight - 300) + 'px',
                overflowY: 'auto'
            },
            userId:sessionStorage.getItem("userId"),
            allMachineType:[],/*所有机器型号列表*/
            allBom:[],
            allSupplier:[],/**所有供应商列表 */
            tableData:[],
            loading:false,/**加载参数 */
            keywords:{/**搜索 */
                bom:'',
                bomId:'',
                supplier:'',
                supplierId:'',
                makeNo:''
             },

            pagination:{/**分页 */
                pageSize:10,
                currentPage:1,
                total:0
            },
            dialog:{/**弹框配置 */
                title:'',
                isShow:false,
            },
            dialog1:{/**弹框1配置 */
                title:'',
                isShow:false,
            },
            dialogForm:{},
            dialogForm1:{},
            isCheckedList:[/**订单审核参数 */
                {
                    label:'通过',
                    value:'1'
                },
                {
                    label:'不通过',
                    value:'0'
                }],
            selectList:[],

        }
    },
    created () {
        let self = this;
        self.getTableList();
        cgbHttp.supplierAllList().then(res=>{
             /**获取所有供应商列表 */
             if(res.content.length>0){
                 res.content.forEach(el => {
                     el.value =el.name;
                     self.allSupplier.push({
                         name:el.name,
                         value:el.name,
                         id:el.id
                     });
                 });
             }
        })
         cgbHttp.cgBomAllList().then(res=>{
             /**获取所有bom列表 */
             if(res.content.length>0){
                 res.content.forEach(el => {
                     el.value =el.name;
                     self.allBom.push({
                         name:el.name,
                         value:el.name,
                         id:el.id
                     });
                 });
             }
        })

        cgbHttp.getDrawBomsList().then(res=>{
            self.allMachineType = res.content;
        })
    },
    methods:{
        getTableList(){
            let self = this;
            self.loading=true;
            let data={
                currentPage:self.pagination.currentPage,
                pageSize:self.pagination.pageSize,
                bom:self.keywords.bom!==''?self.keywords.bomId:'',
                supplier:self.keywords.supplier!==''?self.keywords.supplierId:'',
                makeNo:self.keywords.makeNo
            }
            cgbHttp.purcharePlanList(data).then(res=>{
                self.loading=false;
                self.tableData=res.content.records;
                self.pagination.total = res.content.total;
            },error=>{
                 self.loading=false;
            })
        },
        timesFormatter(row, column, cellValue, index){
            return cellValue?this.timestampToTime1(cellValue,'yy-mm-dd'):'';
        },
        isShowDialog(type,row){
            let self = this;
            if(type==='insert'){
                self.dialog.title = '新增';
                self.dialog.isShow=true;
                self.dialogForm={
                    type:'',
                    num:1,
                    needDate:'',
                    makeNo:'',
                }
            }else{
                self.dialog1.title ='编辑';
                self.dialog1.isShow=true;
                self.dialogForm1={
                    id:row.id,
                    makeNo:row.makeNo,
                    sid:row.sid,
                    supplierName:row.supplierName,
                    bid: row.bid,
                    bomName: row.bomName,
                    needNums:row.needNums,
                    stockNums:row.stockNums,
                    planArriveDate:row.planArriveDate?this.timestampToTime1(row.planArriveDate,'yy-mm-dd hh:mm:ss'):'',
                    price:row.price,
                    total:row.total,
                    orderDate:row.orderDate?this.timestampToTime1(row.orderDate,'yy-mm-dd hh:mm:ss'):'',
                    state:row.state,
                    minPurchase:row.minPurchase,
                    payDate:row.payDate?this.timestampToTime1(row.payDate,'yy-mm-dd hh:mm:ss'):'',
                    creator:row.creator,
                    creatorName:row.creatorName,
                    createTime:row.createTime
                }
            }
        },
        handleSizeChange(size){
            this.pagination.currentPage=1;
            this.pagination.pageSize=size;
            this.getTableList();
        },
        handleCurrentChange(current){
            this.pagination.currentPage=current;
            this.getTableList();
        },
        searchData(){
            this.pagination.currentPage=1;
            this.getTableList();
        },
        createPlan(){
           let self = this;
           let data={
               type:self.dialogForm.type,
               num:self.dialogForm.num,
               needDate:self.timestampToTime(self.dialogForm.needDate),
               makeNo:self.dialogForm.makeNo
           }
           cgbHttp.addPurcharePlan(data).then(res=>{
              self.dialog.isShow=false;
               self.getTableList();
               self.$message.success(`采购计划创建成功`)
           },error=>{
                self.$message.error(`采购计划创建失败`)
           })
        },
        handleChange(){},
        checkSuccess(){
           let self = this;
            self.$confirm('是否审核通过?', '提示', {
                confirmButtonClass: 'el-button--warning'
                }).then(() => {
                    let postData=[];
                    self.selectList.forEach(el=>{
                        postData.push(el.id)
                    })
                    cgbHttp.approvesMultiple(postData).then(res=>{
                        self.getTableList();
                        self.$message.success('审核通过！');
                    },error=>{
                        self.$message.error('审核失败！');
                    })
                }).catch(() => {});
        },
        submitClick(){
           let self = this;
            self.dialogForm1.needDate= self.dialogForm1.needDate?this.timestampToTime1(self.dialogForm1.needDate,'yy-mm-dd hh:mm:ss'):'';
            self.dialogForm1.planArriveDate= self.dialogForm1.planArriveDate?this.timestampToTime1(self.dialogForm1.planArriveDate,'yy-mm-dd hh:mm:ss'):'';
            self.dialogForm1.planPaymentTime=self.dialogForm1.planPaymentTime?this.timestampToTime1(self.dialogForm1.planPaymentTime,'yy-mm-dd hh:mm:ss'):'';
            self.dialogForm1.createor=self.userId;
            cgbHttp.updatePurcharePlan(self.dialogForm1).then(res=>{
                self.dialog1.isShow = false;
                self.getTableList();
                self.$message.success('采购计划编辑成功！')
            },error=>{
                 self.$message.error('采购计划编辑失败！')
            })
        },
        searchAsyncSupplier(queryString, callback){
            let results = queryString ?  this.allSupplier.filter(this.createStateFilter(queryString)) : this.allSupplier;
            callback(results);
        },
        searchAsyncBom(queryString, callback){
            let results = queryString ?  this.allBom.filter(this.createStateFilter(queryString)) : this.allBom;
            callback(results);
        },
        querySearchAsync1(queryString, callback){
            let results = queryString ?  this.allSupplier.filter(this.createStateFilter(queryString)) : this.allSupplier;
            callback(results);
        },
        handleSelect1(item){
            this.dialogForm1.supplierName=item.name;
            this.dialogForm1.sid=item.id;
        },
        changeBom(item){
            this.keywords.bom=item.value;
            this.keywords.bomId =item.id;
        },
        changeSupplier(item){
           this.keywords.supplier=item.value;
           this.keywords.supplierId = item.id;
        },
        createStateFilter(queryString) {
            return (state) => {
                return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) !==-1);
            };
        },
        handleSelectionChange(val){
            let self = this;
            self.selectList=val;
        },
        selectable(row,index){
            if(row.state==1){
                return false;
            }else{
                return true;
            }
        },
        checkedPass(row){/**单个审核通过 */
            let self = this;
            self.$confirm('是否审核通过?', '提示', {
                confirmButtonClass: 'el-button--warning'
                }).then(() => {
                   cgbHttp.approveSingle(row.id).then(res=>{
                        self.$message.success('审核通过成功');
                        self.getTableList();
                    },error=>{
                        self.$message.error('审核通过失败');
                    })
                }).catch(() => {});

        }
    }
}
</script>
<style scoped>
.autocomplete-row{
    width:450px;
}
.input-with-select{
    width:240px;
}
.searchBtn{
    background: #409eff !important;
    color:#fff !important;
}
</style>


